import axios from 'axios'
import BaseRes from "../res/BaseRes";

const BASE_URL:string = 'https://core.ztn-tech.com/'

let token:string = ''

export function setToken(t:string) {
    token = t
}

const service = axios.create({
    baseURL: BASE_URL, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 15 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        // @ts-ignore
        config.headers['access-token'] = token
        // @ts-ignore
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'

        if (config.method === 'post') {
            if (!config.data) {
                config.data = {}
            }
        }
        return config
    },
    error => {
        // do something with request error
        console.error(error) // for debug
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const res:BaseRes<any> = response.data
        if (res) {
            return res.data
        }
    })

export default service
